#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/4/15 15:03
# @Author  : Chenmm
# @File    : role.py
# @Software: PyCharm
from app.api import api
from flask import Flask, request, g, jsonify, send_file, session, current_app
from flask_login import login_required, current_user
from app.models import SysRole
from sqlalchemy import or_


# 获取角色下拉列表
@api.route('/roles/options')
@login_required
def getRolesOptions():
    roles = SysRole.query.filter_by(status=1, is_deleted=0).all()
    data = [role.to_option_json() for role in roles if role.id != 1]

    return jsonify(
        {'code': '00000', 'data': data,
         'msg': '一切ok'})


# 获取角色分页列表
@api.route('/roles/page')
@login_required
def getRolePage():
    args = request.args
    pageNum = args.get('pageNum', 1, type=int)  # 页码
    pageSize = args.get('pageSize', 10, type=int) # 每页记录数
    keywords = args.get('keywords', '').strip() # 关键字(角色名称/角色编码)

    # 过滤掉超级管理员，不在前端显示
    query = SysRole.query.filter(SysRole.id != 1)

    if keywords != '':
        query = query.filter(or_(SysRole.name.contains(keywords), SysRole.code.contains(keywords)))

    pagination = query.paginate(page=pageNum, per_page=pageSize, error_out=False)

    roles = pagination.items
    total = pagination.total

    data_list = []
    for role in roles:
        role_dict = role.to_pageination_dict()
        data_list.append(role_dict)

    data = {
        'list': data_list,
        'total': total
    }

    return jsonify(
        {'code': '00000', 'data': data,
         'msg': '一切ok'})
